package com.bbcare.followup.plat.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.ToolUtils;
import com.bbcare.department.plat.entity.Doctor;
import com.bbcare.department.plat.service.IDoctorManagerService;
import com.bbcare.followup.plat.service.IEvaluationWorkOrderService;

/**
 *
 * @name:         EvaluationWorkOrderController.java
 * @author:       tao
 * @createTime:   2017年10月11日
 * @description:  月度评估工单处理类
 * @modify:
 *
 */
@Controller
@RequestMapping("/service/patient")
public class EvaluationWorkOrderController {

	private final Log logger = LogFactory.getLog(EvaluationWorkOrderController.class);

	@Autowired
	IEvaluationWorkOrderService evaluationWorkOrderService;

	@Autowired
	private IDoctorManagerService doctorManagerService;

	// 查询当前用户当月评估记录
	@ResponseBody
	@RequestMapping("/evaluation/workorder/list")
	public Map<String, Object> queryEvaluationRecords(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
		logger.warn("in queryEvaluationRecords----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 创建人

		String phoneNo = jsonData.getString("phoneNo");
		String userName = jsonData.getString("userName");
		String queueId = jsonData.getString("queueId");
		String status = jsonData.getString("status");

		// 排序字段
		String fieldName = jsonData.getString("fieldName");
		if (StringUtils.isBlank(fieldName)) {
			fieldName = "create_time";
		}
		// 升序还是降序
		String order = jsonData.getString("order");
		if (StringUtils.isBlank(order)) {
			order = "desc";
		}
		List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();

		// 查询用户租户id和科室id
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("phoneNo", phoneNo);
		paramMap.put("userName", userName);
//		paramMap.put("page", jsonData.getString("page"));
//		paramMap.put("rows", jsonData.getString("rows"));
		paramMap.put("fieldName", fieldName);
		paramMap.put("order", order);
		paramMap.put("queueId", queueId);
		paramMap.put("status", status);
		paramMap.put("tenantId",tenantId);
        paramMap.put("authorId",authorId);

        // 针对Datatable特殊处理
        String jsonargs = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonargs)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonargs);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("page", jsonTable.getIntValue("start"));
            paramMap.put("rows", jsonTable.getIntValue("length"));
        }else{
        	int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
     		int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 10;
     		paramMap.put("page", rows*(page-1));
            paramMap.put("rows", rows);
        }

        lists = evaluationWorkOrderService.getEvaluationMonthRecords(paramMap);
        int total = 0;
        if(!CollectionUtils.isEmpty(lists)){
        	total = evaluationWorkOrderService.getEvaluationMonthCount(paramMap);
        }

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("draw", draw);
        retMap.put("recordsTotal", total);
        retMap.put("recordsFiltered", total);
        retMap.put("rows",lists);

		return retMap;
	}

	// 查询当前用户当月评估记录
	@ResponseBody
	@RequestMapping("/evaluation/workorder/detail")
	public ResultModel<Object> queryEvaluationRecordDetail(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
		logger.warn("in queryEvaluationRecordDetail----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String workOrderId = jsonData.getString("workOrderId");
        if(StringUtils.isEmpty(workOrderId)){
        	logger.info("out queryEvaluationRecordDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，评估工单id不能为空");
        }

		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        Map<String,Object> paramMap  = new HashMap<String,Object>();
        paramMap.putAll(jsonData);
        paramMap.put("tenantId", tenantId);

        Map<String, Object> retMap = evaluationWorkOrderService.getEvaluationMonthRecordDetail(paramMap);
        if(null == retMap){
        	logger.info("out queryEvaluationRecordDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"评估记录不存在");
        }
		return new ResultModel<Object>(retMap);
	}

	// 查询当前用户当月评估结果
	@ResponseBody
	@RequestMapping("/evaluation/workorder/result")
	public ResultModel<Object> queryEvaluationRecordResult(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
		logger.warn("in queryEvaluationRecordResult----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String workOrderId = jsonData.getString("workOrderId");
        if(StringUtils.isEmpty(workOrderId)){
        	logger.info("out queryEvaluationRecordResult----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，评估工单id不能为空");
        }

        String type = jsonData.getString("type");
        if(StringUtils.isEmpty(type)){
        	logger.info("out queryEvaluationRecordResult----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，查询类型不能为空");
        }

		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        Map<String,Object> paramMap  = new HashMap<String,Object>();
        paramMap.putAll(jsonData);
        paramMap.put("tenantId", tenantId);

        Map<String, Object> retMap = evaluationWorkOrderService.getEvaluationMonthRecordResult(paramMap);
        /*if(null == retMap){
        	logger.info("out queryEvaluationRecordDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"评估记录不存在");
        }*/
        return new ResultModel<Object>(retMap);
	}

	// 查询当前用户 可选评估项目
	@ResponseBody
	@RequestMapping("/evaluation/workorder/optionalresult")
	public ResultModel<Object> queryEvaluationRecordProjects(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
		logger.warn("in queryEvaluationRecordProjects----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String workOrderId = jsonData.getString("workOrderId");
        if(StringUtils.isEmpty(workOrderId)){
        	logger.info("out queryEvaluationRecordProjects----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，评估工单id不能为空");
        }

		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        Map<String,Object> paramMap  = new HashMap<String,Object>();
        paramMap.putAll(jsonData);
        paramMap.put("tenantId", tenantId);

        Map<String, Object> retMap = evaluationWorkOrderService.getEvaluationRecordProjects(paramMap);
        /*if(null == retMap){
        	logger.info("out queryEvaluationRecordDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"评估记录不存在");
        }*/
        return new ResultModel<Object>(retMap);
	}

	// 查询填写或修改各项指导意见
	@ResponseBody
	@RequestMapping("/evaluation/manualguide/modify")
	public ResultModel<Object> queryEvaluationRecordGuideModify(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
		logger.warn("in queryEvaluationRecordGuideModify----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String workOrderId = jsonData.getString("workOrderId");
        if(StringUtils.isEmpty(workOrderId)){
        	logger.info("out queryEvaluationRecordGuideModify----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，评估工单id不能为空");
        }

        String type = jsonData.getString("type");
        if(StringUtils.isEmpty(type)){
        	logger.info("out queryEvaluationRecordGuideModify----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，查询评估类型不能为空");
        }

//        String guide = jsonData.getString("guide");
		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 租户id

        Map<String,Object> paramMap  = new HashMap<String,Object>();
        paramMap.putAll(jsonData);
        paramMap.put("tenantId", tenantId);
        paramMap.put("authorId", authorId);

        Map<String, Object> retMap = evaluationWorkOrderService.evaluationManualModify(paramMap);
		return new ResultModel<Object>(retMap);
	}


	// 订单信息修改  分配医生、修改状态
	@ResponseBody
	@RequestMapping("/evaluation/workorder/doctormodify")
	public ResultModel<Object> queryEvaluationRecordDoctorModify(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
		logger.warn("in queryEvaluationRecordDoctorModify----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String doctorName = jsonData.getString("doctorName");
		String doctorId = jsonData.getString("doctorId");

		if(StringUtils.isEmpty(doctorId) &&  StringUtils.isEmpty(doctorName)){
        	logger.info("out queryEvaluationRecordDoctorModify----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"请指派评估医生");
        }

		String workOrderId = jsonData.getString("workOrderId");
		if(StringUtils.isEmpty(workOrderId) ){
        	logger.info("out queryEvaluationRecordModify----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，工单号不能为空");
        }
//		String status = jsonData.getString("status");
//      String guide = jsonData.getString("guide");

		//如果doctorName = null  根据DOCtTOR id 查询
		if(!StringUtils.isEmpty(doctorId)){
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("id", doctorId);
			Doctor doctor = doctorManagerService.getDoctorById(map);
			if(null ==  doctor){
	        	throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DOCTOR_NOT_EXIST,"入参校验失败，该医生信息不存在");
			}else{
				doctorName = doctor.getDoctorName();
			}
		}

		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 租户id

        Map<String,Object> paramMap  = new HashMap<String,Object>();
//        paramMap.putAll(jsonData);
        paramMap.put("tenantId", tenantId);
        paramMap.put("authorId", authorId);
        paramMap.put("doctorId", doctorId);
        paramMap.put("doctorName", doctorName);
        paramMap.put("workOrderId", workOrderId);
        paramMap.put("status",Constants.EVLATATION_WORKORDER_STATUS_DO);
        Map<String, Object> retMap = evaluationWorkOrderService.evaluationMonthRecordModify(paramMap);
		return new ResultModel<Object>(retMap);
	}

	// 订单信息修改  分配医生、修改状态
	@ResponseBody
	@RequestMapping("/evaluation/workorder/modify")
	public ResultModel<Object> queryEvaluationRecordModify(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
		logger.warn("in queryEvaluationRecordModify----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String status = jsonData.getString("status");
		if(StringUtils.isEmpty(status) ){
        	logger.info("out queryEvaluationRecordModify----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，状态不能为空");
        }

		String workOrderId = jsonData.getString("workOrderId");
		if(StringUtils.isEmpty(workOrderId) ){
        	logger.info("out queryEvaluationRecordModify----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，工单号不能为空");
        }

//			String status = jsonData.getString("status");
//	      String guide = jsonData.getString("guide");

		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 租户id

        Map<String,Object> paramMap  = new HashMap<String,Object>();
//	        paramMap.putAll(jsonData);
        paramMap.put("workOrderId", workOrderId);
        paramMap.put("status", status);
        paramMap.put("tenantId", tenantId);
        paramMap.put("authorId", authorId);

        Map<String, Object> retMap = evaluationWorkOrderService.evaluationMonthRecordModify(paramMap);
		return new ResultModel<Object>(retMap);
	}

	// 队列评估医生查询
	@ResponseBody
	@RequestMapping("/evaluation/doctor/list")
	public ResultModel<Object> queryEvaluationDoctorList(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
		logger.warn("in queryEvaluationDoctorList----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 租户id

        Map<String,Object> paramMap  = new HashMap<String,Object>();
        paramMap.put("tenantId", tenantId);
        paramMap.put("authorId", authorId);

        List<Map<String, Object>> list = evaluationWorkOrderService.getEvaluationDoctorList(paramMap);
        paramMap.clear();
        paramMap.put("doctorList", list);
		return new ResultModel<Object>(paramMap);
	}

}
